package com.td.module.pests.service.library;

import com.td.framework.common.pojo.PageResult;
import com.td.module.pests.controller.admin.library.vo.LibraryCreateReqVO;
import com.td.module.pests.controller.admin.library.vo.LibraryExportReqVO;
import com.td.module.pests.controller.admin.library.vo.LibraryPageReqVO;
import com.td.module.pests.controller.admin.library.vo.LibraryUpdateReqVO;
import com.td.module.pests.convert.library.LibraryConvert;
import com.td.module.pests.dal.dataobject.library.LibraryDO;
import com.td.module.pests.dal.mysql.library.LibraryMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

import static com.td.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.td.module.pests.enums.ErrorCodeConstants.LIBRARY_NOT_EXISTS;

/**
 * 病虫害知识库 Service 实现类
 *
 * @author wangxx
 */
@Service
@Validated
public class LibraryServiceImpl implements LibraryService {

    @Resource
    private LibraryMapper libraryMapper;

    @Override
    public Long createLibrary(LibraryCreateReqVO createReqVO) {
        // 插入
        LibraryDO library = LibraryConvert.INSTANCE.convert(createReqVO);
        libraryMapper.insert(library);
        // 返回
        return library.getId();
    }

    @Override
    public void updateLibrary(LibraryUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateLibraryExists(updateReqVO.getId());
        // 更新
        LibraryDO updateObj = LibraryConvert.INSTANCE.convert(updateReqVO);
        libraryMapper.updateById(updateObj);
    }

    @Override
    public void deleteLibrary(Long id) {
        // 校验存在
        this.validateLibraryExists(id);
        // 删除
        libraryMapper.deleteById(id);
    }

    private void validateLibraryExists(Long id) {
        if (libraryMapper.selectById(id) == null) {
            throw exception(LIBRARY_NOT_EXISTS);
        }
    }

    @Override
    public LibraryDO getLibrary(Long id) {
        return libraryMapper.selectById(id);
    }

    @Override
    public List<LibraryDO> getLibraryList(Collection<Long> ids) {
        return libraryMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<LibraryDO> getLibraryPage(LibraryPageReqVO pageReqVO) {
        return libraryMapper.selectPage(pageReqVO);
    }

    @Override
    public List<LibraryDO> getLibraryList(LibraryExportReqVO exportReqVO) {
        return libraryMapper.selectList(exportReqVO);
    }

}
